package cn.piesat.client;

import cn.piesat.client.constant.cache.LocalCache;
import cn.piesat.client.constant.consist.AppProperties;
import cn.piesat.client.listener.AlgorithmListener;
import cn.piesat.client.model.dto.base.algorithm.DMSClientBean;
import cn.piesat.client.service.SateService;
import cn.piesat.client.utils.ReadMapFormatUtil;
import cn.piesat.client.utils.ReadPropertiesUtil;
import org.apache.commons.io.filefilter.FileFilterUtils;
import org.apache.commons.io.filefilter.HiddenFileFilter;
import org.apache.commons.io.filefilter.IOFileFilter;
import org.apache.commons.io.monitor.FileAlterationMonitor;
import org.apache.commons.io.monitor.FileAlterationObserver;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;

import java.io.File;
import java.util.Arrays;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * 程序启动后
 * 1.扫描算法文件夹中算法配置信息,并向redis上推送
 * 2.创建Apache的文件夹的监听功能
 */
@Component
public class AfterApplicationRunner implements ApplicationRunner {

    @Autowired
    private AppProperties appProperties;

    @Autowired
    private SateService sateService;

    private Logger logger = LoggerFactory.getLogger(AfterApplicationRunner.class);

    @Override
    public void run(ApplicationArguments args) throws Exception {
        //1.先对扫描文件夹
        scanAlgorithmFolder();
        //2.再开启对算法配置文件夹监控
        startListener();
    }

    /**
     * 启动监听算法配置文件夹
     */
    private void startListener() throws Exception {
        // 创建过滤器
        IOFileFilter directories = FileFilterUtils.and(
                FileFilterUtils.directoryFileFilter(),
                HiddenFileFilter.VISIBLE);
        IOFileFilter files = FileFilterUtils.and(
                FileFilterUtils.fileFileFilter(),
                FileFilterUtils.suffixFileFilter(".properties"));
        IOFileFilter filter = FileFilterUtils.or(directories, files);
        // 使用过滤器
        FileAlterationObserver observer = new FileAlterationObserver(new File(appProperties.getAlgorithmScanPath()), filter);
        observer.addListener(new AlgorithmListener(sateService));
        //创建文件变化监听器
        FileAlterationMonitor monitor = new FileAlterationMonitor(TimeUnit.SECONDS.toMillis(1), observer);
        // 开始监控
        monitor.start();
    }

    /**
     * 扫描算法文件夹
     */
    private void scanAlgorithmFolder() {
        File dir = new File(appProperties.getAlgorithmScanPath());
        logger.info("开始执行算法配置扫描");
        if (!dir.exists()) {
            dir.mkdir();
        }
        File[] files = dir.listFiles((file, name) -> name.endsWith(".properties"));
        if(files!=null){
            //获取数据
            Arrays.stream(files).forEach(file -> {
                ReadPropertiesUtil readutil = new ReadPropertiesUtil();
                try {
                    Map<String, String> readMap = readutil.read(file);
                    DMSClientBean algorithmBean = ReadMapFormatUtil.formatDmsClientBean(readMap);
                    if (algorithmBean != null) {
                        //向redis推送算法信息
                        sateService.pushNewAlgorithmInfo(algorithmBean);
                        //本地缓存算法信息
                        LocalCache.algorithmCache.put(algorithmBean.getAlgorithmBean().getAlgorithmIdEng(), algorithmBean);
                    }
                } catch (Exception e) {
                    logger.error(e.getMessage());
                }
            });
        }
    }
}
